<template>
	<view>
		<!-- 绘制二维码 -->
		<canvas canvas-id="qrcode" style="position: absolute;left: -90000rpx;" />
		<u-navbar :is-back="false" :background="{ background: 'rbga(0,0,0,0)' }" immersive title="推广收益" :border-bottom="false" title-color="#fff"></u-navbar>
		<view class="bg"><image src="/static/images/bg-tuiguang.png" mode="widthFix"></image></view>
		<view class="header">
			<view class="info u-f-ac">
				<u-avatar :src="userinfo.avatarUrl"></u-avatar>
				<view>{{ userinfo.nickName }}</view>
			</view>
			<view class="earnings">
				<view>{{ totalMoney || '0.00' }}</view>
				<view>收益（元）</view>
			</view>
			<view class="btn" data-url="./withdraw/withdraw" @tap="$jumpPage"><button type="default">提现</button></view>
		</view>
		<view class="body">
			<view class="tabs-wrap">
				<u-tabs active-color="#FF642A" inactive-color="#999999" :list="list" :is-scroll="false" :current="current" bar-height="10" @change="change"></u-tabs>
			</view>

			<scroll-view class="scroll" scroll-y="true" @scrolltolower="scrolltolowerEvent">
				<view v-if="current === 0" class="list-mac">
					<view v-for="(item, index) in maclist" :key="index" class="item u-f-jsb" @tap="openQrcodePopup(item.originalDeviceCode,item.macCode)">
						<view class="item-l">
							<view class="mac-name">{{ item.macName }}</view>
							<view class="mac-code">{{ item.macCode }}</view>
						</view>
						<image class="code" src="/static/images/icon-qrcode.png" mode="aspectFill"></image>
					</view>
					<view class="no-data" v-if="maclist.length == 0 && maclist != ''">
						<image src="/static/images/noData1.png" mode="widthFix"></image>
						<view>暂无数据</view>
					</view>
				</view>
				<view v-else class="list-earnings">
					<view v-for="(item, index) in records" :key="index" class="item u-f-jsb">
						<view class="item-l">
							<u-avatar :src="item.wxHeadImgUrl || bindedWxInfo.payeeUserPhoto"></u-avatar>
							<view style="margin-left: 20rpx;">
								<view class="nickname">
									<text>{{item.wxNickName || bindedWxInfo.payeeNickName}}</text>
									<text v-show="item.financeAudit">(提现到微信)</text>
								</view>
								<view v-if="item.addTime" class="time">{{item.addTime}}</view>
							</view>
						</view>
						<view class="mark" :class="[item.financeAudit==1?'':'gray']" v-if="item.billType">{{item.financeAudit==1?'审核中':'已打款'}}</view>
						<view :class="[item.billType==0?'add':'minus']">{{item.billType==0?'+':'-'  }}{{item.promoterMoney}}</view>
					</view>
					<view v-if="records.length == 0" style="margin-top: 60rpx;"></view>
					<loading-bar :status="statusList[1]"></loading-bar>
				</view>
			</scroll-view>
		</view>
		<mac-qrcode ref="macQrcode" :macName="theMacName" :codeUrl="codeUrl" @saveEvent="saveImage" @closeEvent="popupClose"></mac-qrcode>
	</view>
</template>

<script>
import macQrcode from '@/components/popup/mac-qrcode.vue';
import loadingBar from '@/components/loading-bar/loading-bar.vue';
import { mapState } from "vuex"
export default {
	components: { macQrcode, loadingBar },
	data() {
		return {
			list: [{ name: '设备码' }, { name: '收益明细' }],
			current: 0,
			qrcodeImg: '', // 二维码图片tmp地址
			statusList: ['loadmore', 'loading'],
			maclist: '',
			records: [],
			totalMoney: '',
			page: 1,
			limit: 20,
			theMacName:'' ,// 选中的设备名称
			codeUrl:'', // 推广员二维码地址
		};
	},
	computed: {
		...mapState(['userinfo','bindedWxInfo']),
	},
	watch: {
		current(newVal) {
			if (newVal == 1) {
				// this.getEarningList();
				!this.records.length && this.getEarningList();
			} else {
				this.getPromotionMaclist();
			}
		}
	},
	onLoad() {
		// 请求微信提现绑定信息
		this.$store.dispatch('requestBindedWxInfo');
		this.getPromotionMaclist();
		uni.authorize({
			scope: 'scope.writePhotosAlbum',
			success: res => {
				console.log(res);
			},
			fail: err => {
				console.log(err);
			}
		});
		uni.$on('withDraw',this.refresh);
		uni.getScreenBrightness({
		    success:  (res) => {
				this.screenLight = res.value;
		    }
		});
		this.$store.dispatch('requestBindedWxInfo');
	},
	onShow() {
		this.refresh();
	},
	onPullDownRefresh() {
		this.refresh();
	},
	onUnload() {
		uni.$off('withDraw');
	},
	methods: {
		refresh() {
			this.page = 1;
			this.records = [];
			this.maclist = [];
			if(this.current==0) {
				this.getPromotionMaclist();
			} else {
				this.getEarningList();
			}
			this.getPromoterProfitMoney();
			setTimeout(() => {
				uni.stopPullDownRefresh();
			}, 1500);
		},
		getEarningList() {
			let { page, limit } = this;
			this.$u.api
				._earningMoneyList({ page, limit })
				.then(res => {
					if (!res.length) {
						this.statusList.splice(this.current, 1, 'nomore');
						return;
					}
					if(res.length < limit) {
						this.statusList.splice(this.current, 1, 'nomore');
					}
					this.records = [...this.records, ...res];
					
				})
				.catch(err => {
					this.statusList.splice(this.current, 1, 'nomore');
				});
		},
		// 查询推广收益
		getPromoterProfitMoney() {
			this.$u.api._getPromoterProfitMoney().then(res => {
				this.totalMoney = res;
			});
		},
		getPromotionMaclist() {
			this.$u.api._getPromotionMaclist().then(res => {
				this.maclist = res; 
			});
		},
		scrolltolowerEvent(e) {
			if (this.current == 0) return;
			this.statusList.splice(this.current, 1, 'loading');
			this.page++;
			this.getEarningList();
		},
		// 打开二维码弹窗
		openQrcodePopup(originalDeviceCode,macCode) {
			this.theMacName = macCode;
			const params = `promoteCode=${this.userinfo.promoteCode}&macCode=${originalDeviceCode}`;
			this.codeUrl = `https://www.wudada.top/fillmp?` + this.$encode(params);
			this.$nextTick(function(){
				this.$refs.macQrcode.open();
				uni.setScreenBrightness({
				    value: 1,
				    success: function () {
				        console.log('success');
				    }
				});
			})
		},
		// 关闭二维码
		popupClose() {
			console.log('关闭弹窗',this.screenLight);
			uni.setScreenBrightness({
			    value: this.screenLight,
			    success: function () {
			        console.log('success');
			    }
			});
		},
		// 保存到相册
		saveImage(url) {
			uni.showLoading({
				title: '保存中'
			});
			this.permissionJudge().then(res => {
				uni.saveImageToPhotosAlbum({
					filePath: url,
					success: res => {
						uni.showToast({
							title: '已保存到相册',
							icon: 'success',
							duration: 2000
						});
					},
					fail: err => {
						console.log(err);
						uni.hideLoading();
					}
				});
			});
		},
		// 判断权限
		permissionJudge() {
			return new Promise((resolve, reject) => {
				uni.getSetting({
					success: res => {
						if (!res.authSetting['scope.writePhotosAlbum']) {
							uni.hideLoading();
							reject();
							uni.showModal({
								title: '提示',
								content: '请开启“允许保存到手机相册”权限',
								confirmText: '确认开启',
								success: res => {
									if (res.confirm) {
										uni.openSetting({
											success(res) {
												console.log(res.authSetting);
											}
										});
									}
								}
							});
						} else {
							resolve();
						}
					},
					fail: err => {
						console.log(err);
						reject();
					}
				});
			});
		},
		change(index) {
			this.current = index;
		}
	}
};
</script>

<style lang="scss">
.no-data {
	margin-top: 160rpx;
}
.bg {
	position: absolute;
	top: 0;
	z-index: -1;

	image {
		width: 100vw;
	}
}

.header {
	position: absolute;
	width: 100vw;
	top: 100rpx;
	padding: 60rpx 30rpx 0 30rpx;

	.info view {
		color: #ffffff;
		margin-left: 20rpx;
	}
	.earnings {
		display: flex;
		align-items: center;
		flex-direction: column;
		margin-top: 20rpx;

		> view:nth-child(1) {
			font-size: 84rpx;
			color: #ffffff;
			font-weight: bold;
		}
		> view:nth-child(2) {
			font-size: 30rpx;
			color: #fffefe;
			font-weight: 600;
		}
	}

	.btn {
		margin-top: 40rpx;
		> button {
			width: 320rpx;
			height: 102rpx;
			line-height: 100rpx;
			background: linear-gradient(180deg, #ff903e, #ff4d1d);
			color: #ffffff;
			border-radius: 100rpx;
			border: 10rpx solid #ffe97c;
			box-sizing: content-box;
		}
	}
}

.body {
	padding-top: 620rpx;

	.tabs-wrap {
		padding-right: 360rpx;
		box-shadow: 0rpx 1rpx 0rpx 1rpx rgba(0, 0, 0, 0.05);
	}
}

.list-mac,
.list-earnings {
	.item {
		font-weight: 600;
		border-bottom: 1rpx solid #e9e9e9;
		margin: 10rpx 40rpx;
		height: 140rpx;
		padding: 20rpx 0;
		.item-l {
			height: 100%;
			display: flex;
			flex-direction: column;
			justify-content: space-between;
		}
		.mac-name {
			color: #999999;
		}
		.mac-code {
			color: #666666;
			font-size: 36rpx;
		}
		.code {
			width: 80rpx;
			height: 80rpx;
		}
		.mark {
			color: red;
			
			&.gray {
				color: #999999;
			}
		}
	}
}

.list-earnings {
	overflow-y: scroll;

	.item-l {
		flex-direction: row !important;
		font-weight: normal !important;

		> view {
			display: flex;
			flex-direction: column;
			justify-content: space-between;
		}

		.nickname {
			color: #333333;
			font-size: 32rpx;
			font-weight: 600;
			display: flex;
			align-items: center;
			
			>text:nth-child(1) {
				width: 130rpx;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
			}
			>text:nth-child(2) {
				color: #999;
				font-size: 26rpx;
			}
		}

		.time {
			color: #999999;
			font-size: 28rpx;
		}
	}
	.add,.minus {
		width: 160rpx;
		color: #ff642a;
		font-size: 40rpx;
		font-weight: 600;
		text-align: right;
		flex-shrink: 1;
	}
	.minus {
		color: #999999;
	}
}

.scroll {
	height: calc(100vh - 720rpx);
}
</style>
